package org.yty.travelagencyredis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.yty.travelagencyredis.Dao.ChatGroupDao;
import org.yty.travelagencyredis.model.Entity.ChatGroup;
import org.yty.travelagencyredis.model.Entity.ChatGroupMember;
import org.yty.travelagencyredis.model.Entity.ChatUser;
import org.yty.travelagencyredis.model.VO.ChatGroupQueryVO;
import org.yty.travelagencyredis.service.ChatGroupMemberService;
import org.yty.travelagencyredis.service.ChatGroupService;
import org.yty.travelagencyredis.service.ChatUserService;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class ChatGroupServiceImpl implements ChatGroupService {
    private final ChatGroupDao chatGroupDao;
    private final MongoTemplate mongoTemplate;
    @Lazy
    @Autowired
    private ChatGroupMemberService chatGroupMemberService;
    @Lazy
    @Autowired
    private ChatUserService chatUserService;

    @Override
    public ChatGroupQueryVO getById(String id) {
        ChatGroup chatGroup = this.chatGroupDao.selectById(id);
        ChatGroupQueryVO result = new ChatGroupQueryVO();
        BeanUtil.copyProperties(chatGroup,result);
        List<ChatGroupMember> chatGroupMemberList = this.chatGroupMemberService.getListByChatGroupId(id);
        List<String> chatUserIdList = chatGroupMemberList.stream().map(elem -> elem.getChatUserId()).toList();
        List<ChatUser> chatUserList = this.chatUserService.getListByIdList(chatUserIdList);
        result.setChatUserList(chatUserList);
        return result;
    }

    @Override
    public boolean save(ChatGroup chatGroup) {
        return this.chatGroupDao.insert(chatGroup);
    }

    @Override
    public boolean update(ChatGroup chatGroup) {
        return this.chatGroupDao.updateById(chatGroup);
    }

    @Override
    public void deleteById(String id) {
        this.chatGroupMemberService.deleteByChatGroupId(id);
        this.chatGroupDao.deleteById(id);
    }
}
